package com.WOWTradeNews.phone;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.WOWTradeNewsTest.R;
import com.WOWTradeNews.Utils;
import com.WOWTradeNews.DataBase.ConstValues;
import com.WOWTradeNews.DataBase.DBManager;
import com.WOWTradeNews.DataBase.News;
import com.WOWTradeNews.DataBase.SystemDBManager;
import com.WOWTradeNews.Util.ImageLoader;
import com.WOWTradeNews.Util.ImageLoader.OnDoneListener;
import com.WOWTradeNews.services.NewsServer;

public class NewsDetail extends Activity implements Runnable, OnClickListener{
    public String _id, title, source, date,htmlData,subject;
    //private WebView myWebView;
    //private NewsDataBase dataBase;
    private ProgressDialog pd;
    private News news;
    private TextView titleTV, sourceTV,dateTV;
    private Button attachmentBtn;
    
//    private LinearLayout imgLayout;
    
    private TextView contents;
    private Button backButton;
    
    private DBManager dbManager;
    private SystemDBManager systemDBManager;
    
	protected static final int MENU_CATEGORY_EXHIBITOR = Menu.FIRST + 1;
	protected static final int MENU_SECRECT_EVENTS = Menu.FIRST + 2;
	protected static final int MENU_TICA_BONUS = Menu.FIRST + 3;
	protected static final int MENU_DIGEST = Menu.FIRST + 4;
	protected static final int MENU_FLOOR_PLAN = Menu.FIRST + 5;
	
	public static final int COST_COIN = 10;
	
	protected TextView topSubject;
	
	private Button ReCountry;
	private Button ReArticle;
	private Button QueHisArt;
	private Button collection;
	
	private Bitmap bitmap;
	private boolean buttonVis;
	
	LinearLayout wordsLin;
	TextView ct;
	
	LinearLayout lin_txhd;
	TextView txhd;
	
	LinearLayout lin_hdgj;
	TextView hdgj;
	
	LinearLayout lin_hddd;
	TextView hddd;
	
	LinearLayout lin_hdsj;
	TextView hdsj;
	int newsType;
	
	ImageView detailImage;
	ImageView detailImage1;
	ImageView detailImage2;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.market_research_detail_phone);
        
        il = new ImageLoader(this);
        Bundle bundle = this.getIntent().getExtras();
        if(bundle!=null){
        	//_id = bundle.getString("newsID");
        	subject = bundle.getString("subject");
        	news = (News)getIntent().getParcelableExtra("news");
        	_id = news.getIid();
        	newsType = bundle.getInt("newsType");
        }
        topSubject = (TextView)findViewById(R.id.subject);
        topSubject.setText(subject);
        
        backButton = (Button) findViewById(R.id.back);
        backButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        
        //dataBase = new NewsDataBase(this);
        //news = dataBase.findByNews(_id);
        
        dbManager = new DBManager(NewsDetail.this, ConstValues.DB_NEWS);
        //news = dbManager.findByIid(_id);
        
        if(news == null) {
        	return;
        }
        
        systemDBManager = new SystemDBManager(NewsDetail.this);
        
        titleTV = (TextView)findViewById(R.id.title);
        sourceTV = (TextView)findViewById(R.id.source);
        dateTV = (TextView)findViewById(R.id.date);
        attachmentBtn = (Button)findViewById(R.id.attachment_btn);
        contents = (TextView) findViewById(R.id.detailContents);
        
        ReCountry  = (Button) findViewById(R.id.ReCountry);
    	ReArticle  = (Button) findViewById(R.id.ReArticle);
    	QueHisArt = (Button) findViewById(R.id.QueHisArt); 
    	collection = (Button) findViewById(R.id.collection);
    	
    	//imageView = (ImageView) findViewById(R.id.detailImage);
    	
    	detailImage = (ImageView) findViewById(R.id.detailImage);
    	detailImage1 = (ImageView) findViewById(R.id.detailImage1);
    	detailImage2 = (ImageView) findViewById(R.id.detailImage2);
    	
    	ReCountry.setOnClickListener(this);
    	ReArticle.setOnClickListener(this);
    	QueHisArt.setOnClickListener(this);
    	collection.setOnClickListener(this);
    	
    	initUI();
        
        //title = news.getTitle();
        //source =news.getSource();
        //date = news.getStartDate();
        //htmlData = news.getContent();
        
        title = news.getSubject();
        date = news.getDatein();
        source = news.getAuthor();
        htmlData = news.getContents();
        contents.setText(htmlData);
        //Log.d("zhaosdfa", "Detail--->>" + htmlData);
        
        /*if(date != null){
        	date = date.replaceAll("T", " ");
        	
        	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd");
        	
        	try {
				Date tempDate = df.parse(date);
				date = df2.format(tempDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }*/
        
        titleTV.setText(title);
        sourceTV.setText(source);
        dateTV.setText(date);
        
        if(source == null){
        	sourceTV.setVisibility(View.GONE);
        }
		pd = new ProgressDialog(this);
		pd.setMessage("載入中...");
		pd.show();
		new Thread(this).start();
    }

    int hastype = 4;
	private void initUI() {
		wordsLin = (LinearLayout) findViewById(R.id.wordsLin);
		wordsLin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(NewsDetail.this, ReCountry.class);
				Bundle bundle = new Bundle();
				bundle.putString("iid", "");
				bundle.putString("country", ct.getText().toString());
				bundle.putBoolean("ct", true);
				intent.putExtras(bundle);
				startActivity(intent); 
			}
		});
		
		ct = (TextView) findViewById(R.id.ct);
		if(news.getKeyWords() != null && !news.getKeyWords().equals("")&& !news.getKeyWords().equals("null")) {
			wordsLin.setVisibility(View.VISIBLE);
			ct.setText(news.getKeyWords());
		} else {
			wordsLin.setVisibility(View.GONE);
		}
		
		lin_txhd = (LinearLayout) findViewById(R.id.lin_txhd);
		txhd = (TextView) findViewById(R.id.txhd);
		if(news.getActive() != null && !news.getActive().equals("") && !news.getActive().equals("null") && newsType == hastype) {
			lin_txhd.setVisibility(View.VISIBLE);
			txhd.setText(news.getActive());
		} else {
			lin_txhd.setVisibility(View.GONE);
		}
		
		lin_hdgj = (LinearLayout) findViewById(R.id.lin_hdgj);
		hdgj = (TextView) findViewById(R.id.hdgj);
		if(news.getCountry() != null && !news.getCountry().equals("") && !news.getCountry().equals("null") && newsType == hastype) {
			lin_hdgj.setVisibility(View.VISIBLE);
			hdgj.setText(news.getCountry());
		} else {
			lin_hdgj.setVisibility(View.GONE);
		}
		
		lin_hddd = (LinearLayout) findViewById(R.id.lin_hddd);
		hddd = (TextView) findViewById(R.id.hddd);
		if(news.getCity() != null && !news.getCity().equals("") && !news.getCity().equals("null") && newsType == hastype) {
			lin_hddd.setVisibility(View.VISIBLE);
			hddd.setText(news.getCity());
		} else {
			lin_hddd.setVisibility(View.GONE);
		}
		
		
		lin_hdsj = (LinearLayout) findViewById(R.id.lin_hdsj);
		hdsj = (TextView) findViewById(R.id.hdsj);
		if(news.getActtime() != null && !news.getActtime().equals("") && !news.getActtime().equals("null") && newsType == hastype) {
			lin_hdsj.setVisibility(View.VISIBLE);
			hdsj.setText(news.getActtime());
		} else {
			lin_hdsj.setVisibility(View.GONE);
		}
		
	}

	@Override
	public void run() {
		String imgUrl = news.getImg1Url();
		bitmap = null;
		if(imgUrl != null && imgUrl.length() > 0) {
			//bitmap = Utils.getUrlBitmapBonus(news.getImg1Url());
			bitmap = news.getImg();
			//imageView.setImageBitmap(bitmap);
			
			//LinearLayout imgLayout = (LinearLayout) findViewById(R.id.detailImageLin);
	    	//imgLayout.setVisibility(View.VISIBLE);
		}
		
		//myWebView = (WebView)findViewById(R.id.myWebView);
		//myWebView.setWebViewClient(new WebViewClient(){});
		
		/*WebSettings websettings = myWebView.getSettings();  
        websettings.setSupportZoom(true);  
        websettings.setBuiltInZoomControls(true);   
        websettings.setJavaScriptEnabled(true);*/  
        final Context myApp = this;        
        /*myWebView.setWebChromeClient(new WebChromeClient() {  
            @Override  
            public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result){  
                new AlertDialog.Builder(myApp)  
                    .setMessage(message)  
                    .setPositiveButton(android.R.string.ok,  
                            new AlertDialog.OnClickListener() {  
                                public void onClick(DialogInterface dialog, int which)  {  
                                    result.confirm();  
                                }  
                            })  
                    .setCancelable(false)  
                    .create()
                    .show();
                return true;  
            };  
        });*/
        htmlData="<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"/></head><body>"+htmlData+"</body></html>";
        htmlData=htmlData.replaceAll("%", "%25");
        //myWebView.loadDataWithBaseURL (null, htmlData, "text/html", "UTF-8",null);
        if(news.getTxt1Url()!=null && news.getTxt1Url().length()>0){
        	buttonVis = true;
        	attachmentBtn.setOnClickListener(new OnClickListener(){
        		public void onClick(View view){
        			String url=news.getTxt1Url();
        			Intent it = Utils.getPdfFileIntent(url);
        			startActivity(it);
        		}
        	});
        }
        else {
        	buttonVis = false;
        	//LinearLayout ll=(LinearLayout)findViewById(R.id.ll);
        	//ll.setVisibility(View.INVISIBLE);
        }
        handler.sendEmptyMessage(0);
        //dataBase.close();
	}
	
	ImageLoader il;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();
			/*if(bitmap != null) {
				detailImage.setImageBitmap(bitmap);
				detailImage.setVisibility(View.VISIBLE);
			} else {
				detailImage.setVisibility(View.GONE);
			}*/
			il.DisplayImage(news.getImg1Url(), detailImage, false, null);
			
			il.DisplayImage(news.getImg2Url(), detailImage1, false,null);
			
			il.DisplayImage(news.getImg3Url(), detailImage2, false, null);
			
		/*	new OnDoneListener() {
				@Override
				public void onDone(Bitmap bitmap1) {
					if(bitmap1 != null) {
						detailImage.setImageBitmap(bitmap1);
						detailImage.setVisibility(View.VISIBLE);
					} else {
						detailImage.setVisibility(View.GONE);
					}
				}
			}*/
			
	    	LinearLayout ll=(LinearLayout)findViewById(R.id.ll);
        	if(!buttonVis)ll.setVisibility(View.INVISIBLE);
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_CATEGORY_EXHIBITOR, 1, "活動快訊");
		menu.add(0, MENU_SECRECT_EVENTS, 2, "商情放送");
		menu.add(0, MENU_TICA_BONUS, 3, "專題研析");
		menu.add(0, MENU_DIGEST, 4, "市調精華");
		menu.add(0, MENU_FLOOR_PLAN, 5, "經貿書訊");

		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		Bundle bundle = new Bundle();

		switch (item.getItemId()) {
		case MENU_CATEGORY_EXHIBITOR:
			bundle.putString("type", "4");
			bundle.putString("subject", "活動快訊");
			startActivity(new Intent(NewsDetail.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_SECRECT_EVENTS:
			bundle.putString("type", "3");
			bundle.putString("subject", "商情放送");
			startActivity(new Intent(NewsDetail.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_TICA_BONUS:
			bundle.putString("type", "2");
			bundle.putString("subject", "專題研析");
			startActivity(new Intent(NewsDetail.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_DIGEST:
			bundle.putString("type", "1");
			bundle.putString("subject", "市調精華");
			startActivity(new Intent(NewsDetail.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_FLOOR_PLAN:
			bundle.putString("type", "5");
			bundle.putString("subject", "經貿書訊");
			startActivity(new Intent(NewsDetail.this, TradeNewsList.class).putExtras(bundle));
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		
		int id = v.getId();
		switch (id) {
		case R.id.ReCountry:
			if(!Utils.isConnect(NewsDetail.this)) {
				Dialog.showDialog(NewsDetail.this, "目前為無網路狀態");
				break;
			}
			String country = news.getCountry();
			if(country == null || country.equals("")) {
				Dialog.showDialog(NewsDetail.this, "無此國家信息");
				break;
			}
			Map<String, String> map = null;
			try {
				map = NewsServer.getCountryMap();
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(NewsDetail.this, "get country failed!", 1).show();
				break;
			}
			if(map == null) break; 
			String iid = map.get(country);
			Log.d("zhaosdfa", "iid" + iid);
			Intent intent = new Intent(NewsDetail.this, ReCountry.class);
			Bundle bundle = new Bundle();
			bundle.putString("iid", iid);
			bundle.putString("country", country);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.ReArticle:
			String country2 = news.getCountry();
			if(country2 == null || country2.equals("")) {
				Dialog.showDialog(NewsDetail.this, "無此國家信息");
				break;
			}
			Intent i = new Intent();
			i.setClass(NewsDetail.this, TradeNewsList.class);
			Bundle bundle2 = new Bundle();
			bundle2.putString("type", "8");
			bundle2.putString("countryName", country2);
			bundle2.putString("subject", "相關活動");
			i.putExtras(bundle2);
			startActivity(i);
			break;
		case R.id.QueHisArt:
			Intent intent2 = new Intent(NewsDetail.this, SearchHistry.class);
			startActivity(intent2);
			
			
			break;
		case R.id.collection:
			int nowCoin = systemDBManager.getMyCoin();
			
			AlertDialog.Builder builder = new AlertDialog.Builder(NewsDetail.this);
			//您當前點數爲：收藏講扣3點。您當前點數不足，請先購買。
			builder.setTitle("提示");
			if(news.isGj())
			if(systemDBManager.inMyFavoritesLsit(news.getIid())) {
				builder.setMessage("該文章已經加入我的收藏");
				builder.setPositiveButton("確定", null);
				builder.show();
				break;
			}
			String t1 = String.format("您當前點數爲：%d,收藏將扣%d點", nowCoin, COST_COIN);
			String t2 = String.format("您當前點數(%d)不足，請先購買", nowCoin);
			String title = nowCoin >= COST_COIN ? t1 : t2;
			builder.setMessage(title);
			builder.setPositiveButton("確定", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					DBManager dbManager = new DBManager(NewsDetail.this, ConstValues.DB_NEWS);
					int nowCoin = systemDBManager.getMyCoin();
					if(nowCoin >= COST_COIN) {
						systemDBManager.addFavorites(news.getIid(), subject,"");
						systemDBManager.setMyCoin(nowCoin - COST_COIN);
						Toast.makeText(NewsDetail.this, "收藏成功，請到我的最愛查看", 1).show();
					} else {
						//Toast.makeText(NewsDetail.this, "test", 1).show();
						Intent intent = new Intent(NewsDetail.this, Billing.class);
						startActivity(intent);
					}
					dbManager.closeDB();
				}
				
			});
			builder.setNegativeButton("取消", null);
			builder.show();
			
			break;

		default:
			break;
		}
		
	}
	
	@Override
	public void onDestroy() {
		dbManager.closeDB();
		super.onDestroy();
	}
}